import React from 'react'
import { Carousel, Spin } from 'antd'
import dashboardService from "containers/dashboard/dashboard.service";

import DefaultBanner from 'images/dashboard/default-banner.jpg'
import DefaultErrorBanner from 'images/dashboard/default-error-banner.jpg'
import {Modal} from "antd/lib/index";
import moment from "moment/moment";
import {connect} from "react-redux";

class CarouselPicture extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false,
      carousels: [],
      carouselHeight: 0,
    }
  }

  componentWillMount() {
    this.getCarouselsByCompany();
    const {imgWidth, imgProportion} = this.props;
    this.setState({carouselHeight: imgWidth * imgProportion})
  }

  //获取轮播图数据
  getCarouselsByCompany = () => {
    const {companyOID} = this.props.loginUser;
    let banner_list = [];
    this.setState({load: true});
    dashboardService.getCarouselsByCompany(companyOID).then(res => {
      if (res.data.length > 0) {
        res.data.map((item, index) => {
          if (!!item.enable === true) {
            let carouselInfo = {
              url: '',
              carouselOID: item.carouselOID,
              imgSrc: item.attachmentDTO.link,
              title: item.title,
              outLink: item.outLink
            };
            banner_list.push(carouselInfo);
          }
        });
      } else {
        banner_list.push({
          url: '',
          carouselOID: '',
          imgSrc: DefaultBanner,
          title: ''
        })
      }
    }).then(() => {
      banner_list.map((item, index) => {
        if (item.outLink && item.carouselOID) {
          dashboardService.getCarouselByID(item.carouselOID).then((res) => {
            if (res.status === 200) {
              item.outLinkUrl = res.data.firstOutLink;
              this.setState({carousels: banner_list});
            }
          })
        }
      });
      this.setState({
        carousels: banner_list
      }, () => {
        this.resizeCarousel();
      });
    })
  };

  //按比例调整图片大小
  resizeCarousel = () => {
    const {carousels, carouselHeight} = this.state;
    const {imgWidth, imgProportion} = this.props;
    carousels.map((item, index) => {
      let img = new Image();
      // 预加载图片获得图片尺寸，并根据比例调整显示高宽
      img.src = item.imgSrc;
      img.onload = () => {
        let {height, width} = img;  //图片尺寸
        if (height + width > 1) {
          if (height / width < imgProportion) {  //需固定高度并且平移x居中图片
            let targetWidth = carouselHeight * width / height;
            item.style = {height: carouselHeight, width: targetWidth, left: -(targetWidth - imgWidth) / 2};
          }
          if (height / width > imgProportion) {  //需固定宽度与底部
            let targetHeight = imgWidth * height / width;
            item.style = {width: imgWidth, height: targetHeight, top: -(targetHeight - carouselHeight) / 2};
          }
          if (height / width === imgProportion) {
            item.style = {width: "100%", height: "100%"}
          }
        }
        this.setState({load: false, carousels: carousels});
      };
      img.onerror = () => {
        item.imgSrc = DefaultErrorBanner;
        item.style = {width: "100%", height: "100%"};
        this.setState({load: false, carousels: carousels});
      }
    });
    this.setState({
      carousels,
      carouselHeight,
    });
  };

  // 公告详情，模态框展示或跳转链接
  goCarouselDetail = (item) => {
    if (!!item.carouselOID) {
      if (item.outLinkUrl) {
        window.open(item.outLinkUrl, '_blank');
      }
      else {
        dashboardService.getCarouselByID(item.carouselOID).then((res) => {
          if (res.status === 200) {
            item.content = res.data.content;
            item.localDate = moment(res.data.createdDate).format('YYYY-MM-DD');
            Modal.info({
              title: item.title,
              content: (
                <div className="carousel-modal">
                  <div dangerouslySetInnerHTML={{__html: item.content}}></div>
                </div>
              )
            });
          }
        });
      }
    }
  };

  render() {
    const {load, carousels, carouselHeight} = this.state;
    let carouselsJSX = [];
    carousels.length > 0 && carousels.map((item) => {
      carouselsJSX.push(
        <div className="carousel" key={item.carouselOID} onClick={() => this.goCarouselDetail(item)}>
          <img src={item.imgSrc} style={item.style}/>
          {item.title && <div className="carousel-title" style={{bottom: 0}}>{item.title}</div>}
        </div>
      )
    });
    return (
      <Spin spinning={load}>
        <Carousel style={{height: carouselHeight}} dots={true} arrows={true} autoplay>
          {carouselsJSX}
        </Carousel>
      </Spin>
    )
  }
}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
  }
}

CarouselPicture.propTypes = {
  imgWidth: React.PropTypes.number.isRequired, //图片宽度
  imgProportion: React.PropTypes.number.isRequired, //图片比例
};

CarouselPicture.defaultProps={
};

export default connect(mapStateToProps)(CarouselPicture)
